var express = require('express');
var router = express.Router();
const jwt = require('jsonwebtoken');
const fs = require('fs');
const path = require('path');
// 数据目录
const dPath = path.resolve(__dirname, '../keygens/')
const private_key = fs.readFileSync(path.join(dPath, 'rsa_private_key.pem'));
const public_key = fs.readFileSync(path.join(dPath, 'rsa_public_key.pem'));

/* GET users listing. */
router.get('/', function(req, res, next) {
  res.render('login', { title: 'User 登录' });
});

router.post('/jwt/login', (req, res) => {
  console.log(req.body);
  const user = {
    "jst": 1,
    "iss": "box",
    "name": "John Doe",
    "uid": "100001"
  }
  let token = jwt.sign(user, 'secret_key', {
    expiresIn: 1*60 //3分钟过期
  });
  res.send({ success: '1', 'tokenid': token });
});

// verify token
router.post('/jwt/verifytoken', (req, res) => {
  //获取前端请求头发送过来的tokenid
  let get_token = req.headers.authorization; 
  if (get_token) {
    //校验token
    jwt.verify(get_token, 'secret_key', function (err, decoded) {
      if (err) {
        //如果tokenid过期则会执行err的代码块
        res.send({ success: false, message: 'Failed to authenticate token.' });
      } else {
        // if everything is good, save to request for use in other routes
        //将解码信息储存于req中方便其他路由使用
        req.decoded = decoded; 
        // authData
        res.send(decoded);
      }
    });
  } else {
    res.send({ success: false, message: 'Token passed.' });
  }
});

router.post('/jwt/login2', (req, res) => {
  console.log(req.body);
  const user = {
    "jst": 1,
    "iss": "box",
    "name": req.body.account,
    "uid": "100001"
  }
  let token = jwt.sign(user, private_key, {
    algorithm: 'RS256',
    expiresIn: 1 * 60 //3分钟过期
  });
  res.send({ code: 200, token, userInfo:{name: 'admin'}});
});

// verify token
router.post('/jwt/verifytoken2', (req, res) => {
  //获取前端请求头发送过来的tokenid
  // let get_token = req.headers.authorization;
  let get_token = req.headers.token;
  console.log(get_token);
  if (get_token) {
    //校验token
    jwt.verify(get_token, public_key, function (err, decoded) {
      if (err) {
        //如果tokenid过期则会执行err的代码块
        res.send({ code: 100, msg: '', success: false});
      } else {
        // if everything is good, save to request for use in other routes
        //将解码信息储存于req中方便其他路由使用
        req.decoded = decoded;
        // authData
        res.send({ code: 200, msg: 'ok', success: true});
      }
    });
  } else {
    res.send({ code: 101, msg: '', success: false });
    // res.send(false);
  }
});

module.exports = router;
